package com.book.web;

import com.book.pojo.Book;
import com.book.pojo.Page;
import com.book.service.BookService;
import com.book.service.impl.BookServiceImpl;
import com.book.utils.WebUtils;
import com.sun.org.apache.bcel.internal.util.ClassPath;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class BookServlet extends BaseServlet{
    BookService bookService = new BookServiceImpl();

    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    int pageNo=WebUtils.parseInt(req.getParameter("pageNo"),0);
    //获取请求的参数，封装成为Book对象
        Book book = WebUtils.copyParamBean(req.getParameterMap(),new Book());
        //调用BookService.addBook()保存图书
        bookService.addBook(book);
        //跳到图书页面,使用重定向
        resp.sendRedirect(req.getContextPath()+"/manager/bookServlet?action=page&pageNo="+pageNo);
    }
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求参数id
        int id=WebUtils.parseInt(req.getParameter("id"),0);
        //调用bookService.deleteBookById()删除图书
        bookService.deleteBookById(id);
        //重定向回到图书管理页面
        resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=page&pageNo="+req.getParameter("pageNo"));
    }
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数，封装成为Book对象
        Book book=WebUtils.copyParamBean(req.getParameterMap(),new Book());
        //调用BookService.updateBook(book)修改图书
        bookService.updateBook(book);
        //重定向回图书列表管理页面
        resp.sendRedirect(req.getContextPath() + "/manager/bookServlet?action=page&pageNo="+req.getParameter("pageNo"));
    }
    protected void getBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求的参数，图书编号
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        //调用BookService.queryBookById查询图书
        Book book=bookService.queryBookById(id);
        //保存图书到Request域中
        req.setAttribute("book",book);
        //请求转发到负责修改数据的页面book_edit.jsp
        req.getRequestDispatcher("/pages/manager/book_edit.jsp").forward(req, resp);
    }
    protected void getBookFormer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求的参数，图书编号
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        //调用BookService.queryBookById查询图书
        Book book=bookService.queryBookById(id);
        //解决购物车库存问题,保存图书到request域中
        System.out.println(book.getStock()+""+book.getName());
        req.getSession().setAttribute("formerBook",book.getStock());
//        return book.getStock().toString();
    }
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过bookService查询全部图书
        List<Book> books= bookService.queryBooks();
        //把全部图书保存到Request域中
        req.setAttribute("books",books);
        //请求转发到jsp页面
        req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req, resp);
    }

    /**
     * 处理分页功能
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //获取请求的参数pageNo和pageSize
        int pageNo=WebUtils.parseInt(req.getParameter("pageNo"),1);
        int pageSize=WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        //调用BookService.page(page,pageSize);
        Page<Book> page=bookService.page(pageNo,pageSize);
        page.setUrl("manager/bookServlet?action=page");
        //保存Page对象到Request域中
        req.setAttribute("page",page);
        //请求转发到管理页面
        req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req, resp);
    }
    /**
     *
     用来处理上传的数据
     *
     @param
     req
     *
     @param
     resp
     *
     @throws
     ServletException
     *
     @throws
     IOException
     */
    protected void upload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("被调用");
        //1 先判断上传的数据是否多段数据（只有是多段的数据，才是文件上传的）
        if (ServletFileUpload.isMultipartContent(req)) {
           // 创建 FileItemFactory 工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            // 创建用于解析上传数据的工具类 ServletFileUpload 类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
            // 解析上传的数据，得到每一个表单项 FileItem
                List<FileItem> list = servletFileUpload.parseRequest(req);
            // 循环判断，每一个表单项，是普通类型，还是上传的文件
                for (FileItem fileItem : list) {
                if (fileItem.isFormField()) {
                // 普通表单项
                    System.out.println("表单项的 name 属性值：" + fileItem.getFieldName());
            // 参数 UTF-8.解决乱码问题
                    System.out.println("表单项的 value 属性值：" + fileItem.getString("UTF-8"));
                } else
                {
                    //上传的文件
                    System.out.println("表单项的 name 属性值：" + fileItem.getFieldName());
                    System.out.println("上传的文件名：" + fileItem.getName());
                    fileItem.write(new File( this.getServletContext().getRealPath("/static/img/"+ fileItem.getName())));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
}
